package com.hwua.course.mybatis.jdbc.service.impl;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.hwua.course.mybatis.jdbc.service.JdbcOper;
import com.hwua.course.mybatis.jdbc.util.JdbcUtils;

/*
 * 对于文本，在数据库用 text类型
 * 对于图片，在数据库用longblob类型
 */

public class JdbcOperImpl implements JdbcOper {

    @Override
    public void add(String name, Date date, String sex, String address) {
        // 1 sql语句
        String sql = "insert into user(username,birthday,sex,address) values(?,?,?,?)";
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        try {
            conn = JdbcUtils.getConnection();
            // 某些版本： st = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            st = conn.prepareStatement(sql);
            st.setString(1, name);
            st.setDate(2, date);
            st.setString(3, sex);
            st.setString(4, address);
            int num = st.executeUpdate();
            //如果要获取数据库自动生成的主键
            // rs = st.getGeneratedKeys();
            // if (rs.next()) {
            //     System.out.println(rs.getInt(1));
            // } 
            if (num > 0) {
                System.out.println("插入数据成功！");
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            JdbcUtils.close(conn, st, rs);
        }

    }

    @Override
    public void read(String name) {
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        try {
            String sql = "select * from user where username = ?";
            conn = JdbcUtils.getConnection();
            st = conn.prepareStatement(sql);
            st.setString(1, name);
            rs = st.executeQuery();
            if (rs.next()) {
                String id = rs.getString("id");
                String username = rs.getString("username");
                String address = rs.getString("address");
                System.out.println(id + " -- " + username + " " + address);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            JdbcUtils.close(conn, st, rs);
        }
    }

}
